import {New} from '~/lib/broadcast/on.coffee'
import platform from '@/config/platform.mjs'
#import {encode as r64} from '-/r64.mjs'
import {default as reset} from '~/lib/start.coffee'
import config from '~/store/record.coffee'
import ipc from '~/lib/ipc.coffee'
import {HTTP} from '@/config/site.coffee'
export ON = New(true)

{recbar, camera} = ipc
ON.stop = recbar.cancel

is_camera = =>
  config.src == 'camera'

start = new Promise (resolve)=>
  ON.start = resolve
  return

export default (stream, run)=>
  codec = if config.area then '"avc1.640032"' else 'vp9'

  recorder = new MediaRecorder(
    stream
    {
      mimeType:  'video/webm;codecs='+codec
      videoBitsPerSecond: 2e6
    }
  )
  await start
  run?()

  ON.pause = (pause)=>
    if is_camera()
      n = 0
      video_li = []
      for i in stream.getTracks()
        if pause
          enabled = false
        else
          {kind} = i
          if kind == 'video'
            video_li.push i
          enabled = !!config[kind]
          if enabled
            n += 1
        i.enabled = enabled
      if n == 0 and pause == false
        if video_li.length
          config.video = localStorage.video
          for i from video_li
            i.enabled = true
        else
          broadcast.pause true
          return

    {state} = recorder
    if state.startsWith 'pause'
      if not pause
        recorder.resume()
    else if state == 'recording'
        if pause
          recorder.pause()
    return

  runing = new Map
  begin = +new Date

  #task = r64 parseInt(
  #  begin/1000
  #)
  [upload,end,cancel] = await E.upload 'rec/'+config.src #, task

  #data_begin_time = 0
  n = 0
  recorder.ondataavailable = ({data}) =>
    #time = data_begin_time
    #data_begin_time = new Date() - begin
    runing.set n, do =>
      # 用户id , 开始录制时间(秒) , 当前片段第一帧的时间（毫秒）
      await upload n,data
      runing.delete n
      return
    ++n
    return


  finish_resolve = undefined
  finish = new Promise (resolve)=>
    finish_resolve = resolve
    return

  rec_stop = =>
    try
      recorder.stop()
    catch err
      console.error err
      null
    return

  ON.cancel = =>
    rec_stop()
    cancel().finally(
      =>
        recbar.cancel()
        return
    )
    return

  ON.reset = =>
    rec_stop()
    cancel().finally(
      =>
        reset()
        if is_camera()
          await camera.x_rect()
        return
    )
    return

  ON.stop = =>
    rec_stop()
    recbar.stop(is_camera())
    gc()
    await finish
    stream.getTracks().map (i)=>
      i.stop()
      return
    gc()
    await ipc.open HTTP+"video_details.html?user_token=#{localStorage.uid}&id="+await end()
    await recbar.end()
    return

  recorder.onstop = =>
    await Promise.all runing.values()
    finish_resolve()
    return


  recorder.onerror = (event) =>
    console.error "record ❌ #{event.error.name}"
    return

  recorder.start 5000 # 每5秒存一次
  return
